package cn.k.advice;

import cn.k.qo.JSONResult;
import com.alibaba.fastjson.JSON;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@ControllerAdvice
public class GlobalExceptionAdvice {

    //处理异常的方法,方法需要贴ExceptionHandler注解
    @ExceptionHandler(RuntimeException.class)
    public String handlerException(RuntimeException e, HttpServletResponse response,

                                   HttpServletRequest request, Model model, HandlerMethod handlerMethod) throws IOException {
        e.printStackTrace();

        ResponseBody annotation = handlerMethod.getMethodAnnotation(ResponseBody.class);
        if (annotation!=null){
            JSONResult jsonResult = new JSONResult(false, e.getMessage());
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(jsonResult));
            return null;
        }

        model.addAttribute("errorMsg",e.getMessage());
        return "common/error";
    }


    //可以自定义异常
    //下载错误xls


}
